
## this is write by qingluan 
# just a inti handler 
# and a tempalte offer to coder

import tornado
import tornado.web
from tornado import websocket
from modules import JsonTool,User,Link
import time


class BaseHandler(tornado.web.RequestHandler):

    def prepare(self):
        self.db = self.settings['db']
        self.user = User()
        self.linker = Link(self.settings["self_ip"])
        self.ip = self.settings['self_ip']

    def get_current_user(self):
        return (self.get_cookie('user'),self.get_cookie('passwd'))
    def get_current_secure_user(self):
        return (self.get_cookie('user'),self.get_secure_cookie('passwd'))
    def set_current_seccure_user_cookie(self,user,passwd):
        self.set_cookie('user',user)
        self.set_secure_cookie("passwd",passwd)

    def notifer(self,msg,to,From=None,info=False):
        if From == None:
            From = self.request.remote_ip
        socketClient = self.user.getUserByTag[to]
        if  not socketClient:
            print ("no such user found ",to)
            return 

        socketClient.say(msg,who=From,info=info)
                                 
    def get_ajax_argument(self,arg):
        print(self.get_body_argument(arg))
        obj = JsonTool.todict(self.get_body_argument(arg))
        return obj
    def all_to_know(self,msg,who="unkonw"):
        who_off = None
        info = None
        def each_user(user):
            user_connection = self.user.getUserByTag(user)
            if user_connection != None:
                user_connection.say(msg,who=who_off,info=info)

        who_off = who
        info = "every one" 
        list(map(each_user,self.user.contact.keys()))

    @tornado.web.asynchronous
    def link_send(self,f,t,m):
        res = self.linker.broadcast(self.linker.table,JsonTool.tojson({
                "type":"msg",
                "from":f,
                "to":t,
                "msg":m,
                "route":[self.ip],
            }))
        if res == "ok": 
                self.write(JsonTool.responseData("ok"))
        else:
            ss = f+"<h3>"+t+"</h3>"+"<i>"+m+"</i>"
            self.write( ss +"</br><b>" + "this ID not login "+"</b")

        self.finish()

           
class BaseWebSocketHandler(websocket.WebSocketHandler):
    def prepare(self):
        self.ip = self.request.remote_ip
        self.user = User()
    

    def open(self):
        self.user.login(self.ip,self)

    def on_close(self):
        print(self.ip,"is out in our Network")
        user_tag = self.user.getIp_TagByAnother(self.ip,by="ip")
        self.user.logout(user_tag)
        self.all_to_know(" offline " ,user_tag,info="off") 

    def say(self,msg,who="unknow",info=False):
        user = self.user.getIp_TagByAnother(self.ip,by="ip")
        print(who,'to',user,msg,info)
        msg = time.asctime() + "::" + who + "::" + msg
        if info:
            msg += "::"+info
        print(msg)
        self.write_message((msg).encode("utf8"))

    def all_to_know(self,msg,who="unkonw",info=False):
        who_off = None
        info = None
        def each_user(user):
            print(user)
            user_connection = self.user.getUserByTag(user)
            if user_connection != None :
                user_connection.say(msg,who=who_off,info=info)

        who_off = who
        users = self.user.contact.keys()
        info = msg 
        list(map(each_user,users))

    @tornado.web.asynchronous
    def on_message(self,msg):
        obj = JsonTool.todict(msg) 
        if obj['type'] == "changeTag":
            self.user.setTag(self.ip,obj['tag'])
            print('changed ok ',self.user.contact)
        print("you said ",msg)
        


class IndexHandler(BaseHandler):
    
    def prepare(self):
        super(IndexHandler,self).prepare()
        self.template = "template/index.html"

    @tornado.web.asynchronous
    def get(self):
        print(self.settings["self_ip"])
        return self.render(self.template,post_page="/",**{
                "ip":self.settings["self_ip"]
            })

    @tornado.web.asynchronous
    def post(self):
        # you should get some argument from follow 
        post_args = self.get_argument("obj")

        # .....
        print(post_args)

        # self.redirect()  # redirect or reply some content
        self.write("ok")
        self.finish()
    


class NotyHandler(BaseWebSocketHandler):
    
    pass


class SendMsgHandler(BaseHandler):
    def prepare(self):
        super(SendMsgHandler,self).prepare()
        self.template = "template/sendmsg.html"

    @tornado.web.asynchronous    
    def get(self,From,to,msg):
        ss = From+"<h3>"+to+"</h3>"+"<i>"+msg+"</i>"
        user_instance = self.user.getUserByTag(to)
        print(ss)
        if  user_instance == None:
            self.link_send(From,to,msg)

        else:
            user_instance.say(msg,who=From)
            self.write(ss.encode())
            self.finish()

    @tornado.web.asynchronous
    def post(self):
    # you should get some argument from follow 
        post_args = self.get_argument("obj")
        # .....
    # self.redirect()  # redirect or reply some content
        if post_args["type"] == "msg":
            f = post_args["from"]
            m = post_args["msg"]
            t = post_args["to"]
            user_connection = self.user.getUserByTag(t)
            if user_connection:
                user_connection.say(m,who=f)
                self.write(JsonTool.responseData("ok"))
            else:
                self.link_send(f,t,m)   
 
            # self.redirect()  # redirect or reply some content
        else:
            self.write(JsonTool.responseData("error"))
        self.finish()
       



class SearchHandler(BaseHandler):
    
    def prepare(self):
        super(SearchHandler,self).prepare()
        self.template = "template/search.html"

    @tornado.web.asynchronous
    def get(self):
        res = JsonTool.tojson({
            "res":self.user.contact.keys(),
        })
        self.write(res) 
        self.finish()

    @tornado.web.asynchronous
    def post(self):
        # you should get some argument from follow 
        # .....
        post_args = self.get_ajax_argument("obj")

        if (post_args["type"] == "search"):
            print(post_args)
            res = JsonTool.tojson({
                "res":self.user.contact.keys(),
            })
            print("get : ", res)
            # self.redirect()  # redirect or reply some content
            self.write(res)
            self.finish()
        elif (post_args["type"] == "servers"):
            print(post_args)
            res = JsonTool.tojson({
                "res":list(self.linker.table),
                })
            print("servers :",res)
            self.write(res)
            self.finish()
        
    



class InfoHandler(BaseHandler):
    
    def prepare(self):
        super(InfoHandler,self).prepare()
        self.template = "template/info.html"

    def get(self):
        return self.render(self.template,post_page="/info")

    @tornado.web.asynchronous
    def post(self):
        # you should get some argument from follow 
        post_args = self.get_ajax_argument("obj")
        who_off = post_args["name"]
        info = post_args["content"]        
        self.all_to_know(info,who=who_off)


        # .....

        # self.redirect()  # redirect or reply some content
        self.write("good bye ~~~ world")
        self.finish()
    



class SendajaxmsgHandler(BaseHandler):
    
    def prepare(self):
        super(SendajaxmsgHandler,self).prepare()
        self.template = "template/sendajaxmsg.html"

    def get(self):
        return self.render(self.template,post_page="/sendajaxmsg")

    @tornado.web.asynchronous
    def post(self):
        # you should get some argument from follow 
        post_args = self.get_ajax_argument("obj")
        # .....
        if post_args["type"] == "msg":
            t = None
            f = None
            m = None
            try:
                f = post_args["from"]
                m = post_args["msg"]
                t = post_args["to"]
            except KeyError:
                print("need msg , from , or to")
            user_connection = self.user.getUserByTag(t)
            if user_connection:
                user_connection.say(m,who=f)
                self.write(JsonTool.responseData("ok"))
            else:
                self.write(JsonTool.responseData("no Such ID"))

        # self.redirect()  # redirect or reply some content
            
        else:
            self.write(JsonTool.responseData("error"))
        self.finish()
    



class ToallHandler(BaseHandler):
	
	def prepare(self):
		super(ToallHandler,self).prepare()
		self.template = "template/toall.html"

	def get(self,who,msg):
                self.all_to_know(msg,who=who)
		return self.render(self.template,post_page="/toall",**{
                        'msg':msg,
                        'who':who,
                    })

	@tornado.web.asynchronous
	def post(self):
		# you should get some argument from follow 
		post_args = self.get_argument("some_argument")
		# .....

		# self.redirect()  # redirect or reply some content
		self.write("hello world")
	



class LinksHandler(BaseHandler):
	
	def prepare(self):
		super(LinksHandler,self).prepare()
		self.template = "template/links.html"

        @tornado.web.asynchronous
	def get(self,from_ip,msg):
                
                print("\nhere:",from_ip,msg)
                route , msg_obj = self.linker.recived_msg(from_ip,msg)
                if route == False:
                    self.write(JsonTool.responseData("no"))
                    self.finish()

                user_con =  self.user.getUserByTag(msg_obj["to"])
                if user_con:
                    user_con.say(msg_obj["msg"],who=msg_obj["from"])
                    self.write(JsonTool.responseData("ok"))
                    self.finish()
                    return 
                else:
                    print("not found ,go on...")

                
                if self.linker.broadcast(route,JsonTool.tojson(msg_obj)) == "ok":
                    self.write(JsonTool.responseData("ok"))
                    self.finish()
                else:
                    self.write(JsonTool.responseData("Not found"))
                    self.finish()

                
                    

	@tornado.web.asynchronous
	def post(self):
		# you should get some argument from follow 
		post_args = self.get_argument("some_argument")
		# .....

		# self.redirect()  # redirect or reply some content
		self.write("hello world")
	



class LinkreplyHandler(BaseHandler):
	
	def prepare(self):
		super(LinkreplyHandler,self).prepare()
		self.template = "template/linkreply.html"

        @tornado.web.asynchronous
	def get(self,cmd,to):
            if cmd == "link":
                res = self.linker.link_start(to)
                self.write(JsonTool.responseData(res+"::"+to))
                self.finish()
            if cmd == "search":
                self.write(JsonTool.responseData(self.linker.table))
                self.finish()
		

	@tornado.web.asynchronous
	def post(self):
		# you should get some argument from follow 
		post_args = self.get_argument("some_argument")
		# .....

		# self.redirect()  # redirect or reply some content
		self.write("hello world")
	



class LinkstartHandler(BaseHandler):
	
	def prepare(self):
		super(LinkstartHandler,self).prepare()
		self.template = "template/linkstart.html"

        @tornado.web.asynchronous
	def get(self,port):
                self.linker.link_re(self.request.remote_ip+":"+port)
                self.write(JsonTool.responseData("ok"))
                self.finish()

	@tornado.web.asynchronous
	def post(self):
		# you should get some argument from follow 
		post_args = self.get_argument("some_argument")
		# .....

		# self.redirect()  # redirect or reply some content
		self.write("hello world")
	
